<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Silence
 * Date: 3/30/12
 * Time: 1:13 AM
 * To change this template use File | Settings | File Templates.
 */
include_once('api.php');
class Event
{
    private $data = null;
    private $event_basic = null;
    private $event_people = null;
    private $event_budget = null;

    const TABLE = "event";

    function __construct($data)
    {
        check_attr($data);
        $this->data = $data;
        if (!isset($data->id)) {
            $this->create();
        }
        $this->event_basic = new EventBasic($this->data);
    }

    public function create()
    {
        $d = &$this->data;
        check_attr($d, 'parentId');

        $pair = get_keys_values_pair($this->data, $this->fields(TRUE));
        $ks = implode("`,`", $pair[0]);
        $vs = implode("','", $pair[1]);
        $t = self::TABLE;
        $parentId = $this->data->parentId;
        $sql_turn_into_parent = "UPDATE $t SET `leaf` = 0 WHERE `id` = $parentId";
        $sql = "INSERT INTO `$t` (`$ks`) VALUES ('$vs')";

        if (mysql_query($sql) !== FALSE) {
            $d->id = mysql_insert_id();

            if (mysql_query($sql_turn_into_parent) === FALSE) {
                throw new ErrorException("Create event (update parents) failure.");
            }

            $event_basic = new EventBasic($d);
            $event_basic->create();

        } else {
            throw new ErrorException("Create event failure.");
        }
    }

    public function read($keys, $allow_leaf, $recursive)
    {
        check_attr($this->data, "id");
        $t = self::TABLE;
        $id = $this->data->id;
        $ret = array();

        if ($id == "root") {
            return array(
                'children' => array(
                    array(
                        'id' => 0,
                        'name' => 'My Folders',
                        'expanded' => TRUE
                    ),
                    array(
                        'id' => -1,
                        'name' => 'Recycle Bin',
                        'iconCls' => 'recyclebin x-tree-node-icon',
                    ),
                )
            );
        }

        if ((int)$id > 1) {
            $ret = $this->load($keys);
        }

        if ($id == -1) {
            $sql = "SELECT * FROM $t WHERE `status` = 0";
        } else {
            $sql = "SELECT * from $t WHERE `parentId` = $id AND `status` = 1";
        }
        if ($allow_leaf == FALSE) {
            $sql .= " AND leaf = 0";
        }

        $res = mysql_query($sql);
        while ($child_data = mysql_fetch_object($res))
        {
            $child = new Event($child_data);
            if ($recursive)
                $ret['children'][] = $child->read($keys, $allow_leaf, $recursive);
            else
                $ret['children'][] = $child->load($keys);
        }

        if (isset($ret['leaf']) && $ret['leaf'] == 0)
            $ret['leaf'] = false;
        else if (isset($ret['leaf']) && $ret['leaf'] == 1)
            $ret['leaf'] = true;
        return $ret;
    }

    public function load($keys)
    {
        $to_load = array_intersect($keys, $this->fields(TRUE));
        $need_load = FALSE;
        foreach ($to_load as $k) {
            if (!isset($this->data->$k)) {
                $need_load = TRUE;
                break;
            }
        }
        if ($need_load) {
            $id = $this->data->id;
            $t = self::TABLE;
            $sql = "SELECT * FROM $t WHERE `id` = '$id'";
            $res = mysql_query($sql);
            if ($res === FALSE || (!$this->data = mysql_fetch_object($res)))
                throw new ErrorException("Load event failure.");
        }

        $event_data = (array)$this->data;
        $event_basic_data = $this->event_basic->load($keys);

        return array_merge($event_basic_data, $event_data);
    }

    public function update($additional = null)
    {
        check_attr($this->data, "id");

        if ($additional) {
            foreach ($additional as $k => $v) {
                $this->data->$k = $v;
            }
        }

        $pairs = get_key_value_pairs($this->data, $this->fields(FALSE));

        if (strlen($pairs) > 0) {
            $t = self::TABLE;
            $id = $this->data->id;
            $sql = "UPDATE `$t` SET $pairs WHERE `id` = $id";
            if (mysql_query($sql) === FALSE) {
                throw new ErrorException("Update event failure.");
            }
        }
        $this->event_basic->update();
    }

    public function delete()
    {
        check_attr($this->data, "id");
        $t = self::TABLE;
        $id = $this->data->id;
        $sql = "DELETE from `$t` where `id` = $id";
        return mysql_query($sql);
    }

    public static function fields($include_id)
    {
        if ($include_id)
            return array('id', 'parentId', 'leaf', 'status');
        else
            return array('parentId', 'leaf', 'status');
    }
}

class EventBasic
{
    const TABLE = "event_basic";
    private $data = null;

    public function __construct($data)
    {
        check_attr($data, 'id');
        $this->data = $data;
    }

    public function create()
    {
        if (!isset($this->data->start_date)) {
            $this->data->start_date = date("Y-m-d");
            $nextWeek = time() + (7 * 24 * 60 * 60);
            $this->data->end_date = date("Y-m-d", $nextWeek);
        }
        $pair = get_keys_values_pair($this->data, array('id', 'name', 'start_date', 'end_date'));
        $ks = implode("`,`", $pair[0]);
        $vs = implode("','", $pair[1]);
        $t = self::TABLE;
        $sql = "INSERT INTO `$t` (`$ks`) VALUES ('$vs')";
        if (mysql_query($sql) === FALSE) {
            throw new ErrorException("Create event basic failure.");
        }
    }

    public function read()
    {
        check_attr($this->data, "id");

    }

    public function load($keys)
    {
        $to_load = array_intersect($keys, $this->fields(TRUE));
        $need_load = FALSE;
        foreach ($to_load as $k) {
            if (!isset($this->data->$k)) {
                $need_load = TRUE;
                break;
            }
        }
        if ($need_load) {
            $id = $this->data->id;
            $t = self::TABLE;
            $sql = "SELECT * FROM $t WHERE `id` = '$id'";
            $res = mysql_query($sql);
            if ($res === FALSE || (!$this->data = mysql_fetch_object($res)))
                throw new ErrorException("Load event basic failure.");
        }
        return (array)$this->data;
    }

    public function update()
    {
        check_attr($this->data, "id");
        $pairs = get_key_value_pairs($this->data, $this->fields(FALSE));
        if (strlen($pairs) > 0) {
            $t = self::TABLE;
            $id = $this->data->id;
            $sql = "UPDATE `$t` SET $pairs WHERE `id` = $id";
            if (mysql_query($sql) === FALSE) {
                throw new ErrorException("Update event basic failure.");
            }
        }

    }

    public function fields($include_id)
    {
        if ($include_id)
            return array('id', 'name', "start_date", "end_date");
        else
            return array('name', "start_date", "end_date");
    }
}

